#Boa:Dialog:Dialog1

import wx
import wx.grid
import utiles
import consultasBD
from decimal import Decimal

ROJO = (255, 145, 145, 255)
VERDE = (145, 255, 145, 255)
AZUL = (145, 145, 255, 255)
BLANCO = (255, 255, 255, 255)
AMARILLO = (254, 248, 191, 255)
GRIS = ( 220, 220, 220, 255)
NEGRO = ( 0, 0, 0, 255)
VERDENEGRO = ( 47, 79, 79, 255)

def create(parent):
    return Dialog1(parent)

[wxID_DIALOG1, wxID_DIALOG1BUTTON1, wxID_DIALOG1BUTTON2, wxID_DIALOG1BUTTON3, 
 wxID_DIALOG1BUTTON4, wxID_DIALOG1GRID1, wxID_DIALOG1STATICTEXT1, 
 wxID_DIALOG1STATICTEXT10, wxID_DIALOG1STATICTEXT11, wxID_DIALOG1STATICTEXT12, 
 wxID_DIALOG1STATICTEXT13, wxID_DIALOG1STATICTEXT14, wxID_DIALOG1STATICTEXT2, 
 wxID_DIALOG1STATICTEXT3, wxID_DIALOG1STATICTEXT4, wxID_DIALOG1STATICTEXT5, 
 wxID_DIALOG1STATICTEXT6, wxID_DIALOG1STATICTEXT7, wxID_DIALOG1STATICTEXT8, 
 wxID_DIALOG1STATICTEXT9, wxID_DIALOG1TEXTCTRL1, wxID_DIALOG1TEXTCTRL10, 
 wxID_DIALOG1TEXTCTRL11, wxID_DIALOG1TEXTCTRL12, wxID_DIALOG1TEXTCTRL13, 
 wxID_DIALOG1TEXTCTRL2, wxID_DIALOG1TEXTCTRL3, wxID_DIALOG1TEXTCTRL4, 
 wxID_DIALOG1TEXTCTRL5, wxID_DIALOG1TEXTCTRL6, wxID_DIALOG1TEXTCTRL7, 
 wxID_DIALOG1TEXTCTRL8, wxID_DIALOG1TEXTCTRL9, 
] = [wx.NewId() for _init_ctrls in range(33)]

class Dialog1(wx.Dialog):
    def _init_ctrls(self, prnt):
        # generated method, don't edit
        wx.Dialog.__init__(self, id=wxID_DIALOG1, name='', parent=prnt,
              pos=wx.Point(380, 128), size=wx.Size(832, 335),
              style=wx.DEFAULT_DIALOG_STYLE, title='Normalizar PTC')
        self.SetClientSize(wx.Size(824, 308))

        self.staticText1 = wx.StaticText(id=wxID_DIALOG1STATICTEXT1,
              label='PTC', name='staticText1', parent=self, pos=wx.Point(16, 8),
              size=wx.Size(19, 13), style=0)

        self.textCtrl1 = wx.TextCtrl(id=wxID_DIALOG1TEXTCTRL1, name='textCtrl1',
              parent=self, pos=wx.Point(16, 24), size=wx.Size(72, 21), style=0,
              value='')

        self.button1 = wx.Button(id=wxID_DIALOG1BUTTON1, label='Buscar',
              name='button1', parent=self, pos=wx.Point(96, 24),
              size=wx.Size(75, 23), style=0)
        self.button1.Bind(wx.EVT_BUTTON, self.OnBuscar, id=wxID_DIALOG1BUTTON1)

        self.button4 = wx.Button(id=wxID_DIALOG1BUTTON4, label='Limpiar',
              name='button4', parent=self, pos=wx.Point(740, 24),
              size=wx.Size(75, 23), style=0)
        self.button4.Bind(wx.EVT_BUTTON, self.OnLimpiar, id=wxID_DIALOG1BUTTON4)

        self.button3 = wx.Button(id=wxID_DIALOG1BUTTON3, label='Guardar',
              name='button3', parent=self, pos=wx.Point(412, 272),
              size=wx.Size(75, 23), style=0)
        self.button3.Enable(False)
        self.button3.Bind(wx.EVT_BUTTON, self.OnGuardar, id=wxID_DIALOG1BUTTON3)

        self.button2 = wx.Button(id=wxID_DIALOG1BUTTON2, label='Salir',
              name='button2', parent=self, pos=wx.Point(740, 272),
              size=wx.Size(75, 23), style=0)
        self.button2.Bind(wx.EVT_BUTTON, self.OnSalir, id=wxID_DIALOG1BUTTON2)

        self.staticText2 = wx.StaticText(id=wxID_DIALOG1STATICTEXT2,
              label='Cod.Sussan', name='staticText2', parent=self,
              pos=wx.Point(16, 56), size=wx.Size(57, 13), style=0)

        self.textCtrl2 = wx.TextCtrl(id=wxID_DIALOG1TEXTCTRL2, name='textCtrl2',
              parent=self, pos=wx.Point(16, 72), size=wx.Size(72, 21), style=0,
              value='')
        self.textCtrl2.SetEditable(False)

        self.staticText3 = wx.StaticText(id=wxID_DIALOG1STATICTEXT3,
              label='ID Proveedor', name='staticText3', parent=self,
              pos=wx.Point(96, 96), size=wx.Size(64, 13), style=0)

        self.textCtrl3 = wx.TextCtrl(id=wxID_DIALOG1TEXTCTRL3, name='textCtrl3',
              parent=self, pos=wx.Point(96, 112), size=wx.Size(80, 21), style=0,
              value='')
        self.textCtrl3.SetEditable(False)

        self.staticText4 = wx.StaticText(id=wxID_DIALOG1STATICTEXT4,
              label='Descripcion', name='staticText4', parent=self,
              pos=wx.Point(96, 56), size=wx.Size(54, 13), style=0)

        self.textCtrl4 = wx.TextCtrl(id=wxID_DIALOG1TEXTCTRL4, name='textCtrl4',
              parent=self, pos=wx.Point(96, 72), size=wx.Size(304, 21), style=0,
              value='')
        self.textCtrl4.SetEditable(False)

        self.staticText5 = wx.StaticText(id=wxID_DIALOG1STATICTEXT5,
              label='Precio 1', name='staticText5', parent=self,
              pos=wx.Point(408, 56), size=wx.Size(38, 13), style=0)

        self.textCtrl5 = wx.TextCtrl(id=wxID_DIALOG1TEXTCTRL5, name='textCtrl5',
              parent=self, pos=wx.Point(408, 72), size=wx.Size(72, 21), style=0,
              value='')
        self.textCtrl5.SetEditable(False)

        self.textCtrl6 = wx.TextCtrl(id=wxID_DIALOG1TEXTCTRL6, name='textCtrl6',
              parent=self, pos=wx.Point(480, 72), size=wx.Size(72, 21), style=0,
              value='')
        self.textCtrl6.SetEditable(False)

        self.staticText6 = wx.StaticText(id=wxID_DIALOG1STATICTEXT6,
              label='Precio 2', name='staticText6', parent=self,
              pos=wx.Point(480, 56), size=wx.Size(38, 13), style=0)

        self.staticText7 = wx.StaticText(id=wxID_DIALOG1STATICTEXT7,
              label='Estacion', name='staticText7', parent=self,
              pos=wx.Point(560, 56), size=wx.Size(40, 13), style=0)

        self.staticText8 = wx.StaticText(id=wxID_DIALOG1STATICTEXT8,
              label='Anio', name='staticText8', parent=self, pos=wx.Point(656,
              56), size=wx.Size(21, 13), style=0)

        self.textCtrl7 = wx.TextCtrl(id=wxID_DIALOG1TEXTCTRL7, name='textCtrl7',
              parent=self, pos=wx.Point(560, 72), size=wx.Size(96, 21), style=0,
              value='')
        self.textCtrl7.SetEditable(False)

        self.textCtrl8 = wx.TextCtrl(id=wxID_DIALOG1TEXTCTRL8, name='textCtrl8',
              parent=self, pos=wx.Point(656, 72), size=wx.Size(56, 21), style=0,
              value='')
        self.textCtrl8.SetEditable(False)

        self.staticText9 = wx.StaticText(id=wxID_DIALOG1STATICTEXT9,
              label='Precio Compra', name='staticText9', parent=self,
              pos=wx.Point(408, 96), size=wx.Size(69, 13), style=0)

        self.staticText10 = wx.StaticText(id=wxID_DIALOG1STATICTEXT10,
              label='Grupo', name='staticText10', parent=self, pos=wx.Point(560,
              96), size=wx.Size(29, 13), style=0)

        self.staticText11 = wx.StaticText(id=wxID_DIALOG1STATICTEXT11,
              label='Temporada', name='staticText11', parent=self,
              pos=wx.Point(608, 96), size=wx.Size(54, 13), style=0)

        self.textCtrl9 = wx.TextCtrl(id=wxID_DIALOG1TEXTCTRL9, name='textCtrl9',
              parent=self, pos=wx.Point(408, 112), size=wx.Size(72, 21),
              style=0, value='')
        self.textCtrl9.SetEditable(False)

        self.textCtrl10 = wx.TextCtrl(id=wxID_DIALOG1TEXTCTRL10,
              name='textCtrl10', parent=self, pos=wx.Point(560, 112),
              size=wx.Size(48, 21), style=0, value='')
        self.textCtrl10.SetEditable(False)

        self.textCtrl11 = wx.TextCtrl(id=wxID_DIALOG1TEXTCTRL11,
              name='textCtrl11', parent=self, pos=wx.Point(608, 112),
              size=wx.Size(104, 21), style=0, value='')
        self.textCtrl11.SetEditable(False)

        self.staticText12 = wx.StaticText(id=wxID_DIALOG1STATICTEXT12,
              label='Talle', name='staticText12', parent=self, pos=wx.Point(720,
              96), size=wx.Size(22, 13), style=0)

        self.textCtrl12 = wx.TextCtrl(id=wxID_DIALOG1TEXTCTRL12,
              name='textCtrl12', parent=self, pos=wx.Point(720, 112),
              size=wx.Size(48, 21), style=0, value='')
        self.textCtrl12.SetEditable(False)

        self.textCtrl13 = wx.TextCtrl(id=wxID_DIALOG1TEXTCTRL13,
              name='textCtrl13', parent=self, pos=wx.Point(768, 112),
              size=wx.Size(48, 21), style=0, value='')
        self.textCtrl13.SetEditable(False)

        self.staticText13 = wx.StaticText(id=wxID_DIALOG1STATICTEXT13,
              label='Color', name='staticText13', parent=self, pos=wx.Point(768,
              96), size=wx.Size(25, 13), style=0)

        self.grid1 = wx.grid.Grid(id=wxID_DIALOG1GRID1, name='grid1',
              parent=self, pos=wx.Point(96, 144), size=wx.Size(304, 152),
              style=0)
        self.grid1.Bind(wx.EVT_SET_FOCUS, self.OnGridFocus)

        self.staticText14 = wx.StaticText(id=wxID_DIALOG1STATICTEXT14,
              label='NOTA: esta operacion puede demorar algunos minutos',
              name='staticText14', parent=self, pos=wx.Point(184, 24),
              size=wx.Size(306, 13), style=0)
        self.staticText14.SetFont(wx.Font(8, wx.SWISS, wx.NORMAL, wx.BOLD,
              False, 'Tahoma'))

    def __init__(self, parent):
        self._init_ctrls(parent)
        self.crearGrilla()

    def OnSalir(self, event):
        self.Close()

    def crearGrilla(self):
        #sucursal,stock
        #0        1
        columnas = ['Sucursal','Stock']
        self.grid1.CreateGrid(1,len(columnas))
        for i, col in enumerate(columnas): 
            self.grid1.SetColLabelValue(i, col)
        self.ajustarAnchoColumnas()
        self.grid1.EnableEditing(False)
        self.grid1.SetSelectionMode(wx.grid.Grid.wxGridSelectRows)
        self.grid1.Refresh()

    def ajustarAnchoColumnas(self):
        for y in xrange(self.grid1.GetNumberCols()):
            self.grid1.AutoSizeColumn(y,True)

    def OnLimpiar(self, event):
        self.textCtrl1.SetLabel("")
        self.textCtrl2.SetLabel("")
        self.textCtrl3.SetLabel("")
        self.textCtrl4.SetLabel("")
        self.textCtrl5.SetLabel("")
        self.textCtrl6.SetLabel("")
        self.textCtrl7.SetLabel("")
        self.textCtrl8.SetLabel("")
        self.textCtrl9.SetLabel("")
        self.textCtrl10.SetLabel("")
        self.textCtrl11.SetLabel("")
        self.textCtrl12.SetLabel("")
        self.textCtrl13.SetLabel("")
        self.grid1.ClearGrid()
        for fil in xrange(self.grid1.GetNumberRows()):
            self.grid1.DeleteRows()
        self.grid1.AppendRows()
        self.button3.Enable(False)
        self.textCtrl1.SetFocus()

    def verificarPTClocal(self, ptc):
        sql = "SELECT * FROM producto_talle_color WHERE id='"+ptc+"' "
        resultados = consultasBD.ordenCrudaDict(sql)
        if resultados == None or resultados == () or len(resultados) == 0:
            return False
        codsussan = resultados[0]["codsussan"]
        sql = "SELECT * FROM productos WHERE codsussan='"+codsussan+"' "
        resultados = consultasBD.ordenCrudaDict(sql)
        if resultados == None or resultados == () or len(resultados) == 0:
            return False
        sql = "SELECT * FROM stock WHERE ptc='"+ptc+"' "
        resultados = consultasBD.ordenCrudaDict(sql)
        if resultados == None or resultados == () or len(resultados) == 0:
            return False
        return True

    def OnGridFocus(self, event):
        self.textCtrl1.SetFocus()
            
    def OnBuscar(self, event):
        if self.textCtrl1.GetLabel()=="":
            utiles.mensaje(None,"Debe especificar un PTC")
            self.textCtrl1.SetFocus()
            return
        if self.verificarPTClocal(self.textCtrl1.GetLabel()):
            utiles.mensaje(None,"El PTC no necesita ser normalizado")
            self.textCtrl1.SetFocus()
            return
        
        ptc = self.textCtrl1.GetLabel()
        r1 = "SELECT * FROM producto_talle_color ptc, productos p, stock s \n"
        r2 = "WHERE ptc.id='"+ptc+"' \n"
        r3 = "      AND ptc.codsussan=p.codsussan AND ptc.id=s.ptc"
        sql = r1+r2+r3
        
        resultado,conexion = consultasBD.ordenCrudaRemota(sql,0)
        
        if not conexion:
            utiles.mensaje(None,"No hay conexion con Casa Central")
            self.OnLimpiar(None)
            return

        if resultado == () or resultado == None or len(resultado) != 4:
            r1 = "No hay informacion de este PTC\n"
            r2 = "o la informacion existente es incompleta"
            texto = r1+r2
            utiles.mensaje(None,texto)
            self.OnLimpiar(None)
            return
            
        print "Mostrando resultados"
        
        producto = resultado[0]
        
        codsussan = str(producto[1])
        talle = str(producto[2])
        color = str(producto[3])
        temporada = str(producto[4])
        idproveedor = str(producto[6])
        descri = str(producto[7])
        precio1 = str(producto[8])
        precio2 = str(producto[9])
        estacion = str(producto[10])
        anio = str(producto[11])
        grupo = str(producto[12])
        preciocompra = str(producto[13])

        self.textCtrl2.SetLabel(codsussan)
        self.textCtrl3.SetLabel(idproveedor)
        self.textCtrl4.SetLabel(descri)
        self.textCtrl5.SetLabel(precio1)
        self.textCtrl6.SetLabel(precio2)
        self.textCtrl7.SetLabel(estacion)
        self.textCtrl8.SetLabel(anio)
        self.textCtrl9.SetLabel(preciocompra)
        self.textCtrl10.SetLabel(grupo)
        self.textCtrl11.SetLabel(temporada)
        self.textCtrl12.SetLabel(talle)
        self.textCtrl13.SetLabel(color)
        
        fila = 0
        for item in resultado:
            sucursal = str(item[17])
            stock = str(item[18])
            self.grid1.SetCellValue(fila,0,sucursal)
            self.grid1.SetCellValue(fila,1,stock)
            
            self.grid1.SetCellAlignment(fila,0,wx.ALIGN_RIGHT,wx.ALIGN_CENTRE)
            self.grid1.SetCellAlignment(fila,1,wx.ALIGN_RIGHT,wx.ALIGN_CENTRE)
            self.grid1.AppendRows()
            fila = fila + 1

        self.ajustarAnchoColumnas()
        self.button3.Enable(True)

    def OnGuardar(self, event):
        ptc = self.textCtrl1.GetLabel()
        codsussan = self.textCtrl2.GetLabel()
        idproveedor = self.textCtrl3.GetLabel()
        descri = self.textCtrl4.GetLabel()
        precio1 = self.textCtrl5.GetLabel()
        precio2 = self.textCtrl6.GetLabel()
        estacion = self.textCtrl7.GetLabel()
        anio = self.textCtrl8.GetLabel()
        preciocompra = self.textCtrl9.GetLabel()
        grupo = self.textCtrl10.GetLabel()
        temporada = self.textCtrl11.GetLabel()
        talle = self.textCtrl12.GetLabel()
        color = self.textCtrl13.GetLabel()
        
        sql1 = ""
        sql = "SELECT * FROM producto_talle_color WHERE id='"+ptc+"' "
        resultados = consultasBD.ordenCrudaDict(sql)
        if resultados == None or resultados == () or len(resultados) == 0:
            #como no se ha encontrado info del PTC...
            r1 = "INSERT INTO producto_talle_color(id,codsussan,talle,color,temporada) "
            r2 = "VALUES('"+ptc+"','"+codsussan+"','"+talle+"','"+color+"','"+temporada+"')"
            sql1 = r1+r2
        sql2 = ""
        sql = "SELECT * FROM productos WHERE codsussan='"+codsussan+"' "
        resultados = consultasBD.ordenCrudaDict(sql)
        if resultados == None or resultados == () or len(resultados) == 0:
            #como no se ha encontrado info del PRODUCTO...
            r1 = "INSERT INTO productos(codsussan,proveedor,descri,preciolt1,\n"
            r2 = "       preciolt2,estacion,anio,grupo,preciocompra,temporada) \n"
            r3 = "VALUES('"+codsussan+"','"+idproveedor+"','"+descri+"',\n"
            r4 = "       '"+precio1+"','"+precio2+"','"+estacion+"','"+anio+"',\n"
            r5 = "       '"+grupo+"','"+preciocompra+"','"+temporada+"')"
            sql2 = r1+r2+r3+r4+r5
        sql3 = []
        sql = "SELECT * FROM stock WHERE ptc='"+ptc+"' "
        resultados = consultasBD.ordenCrudaDict(sql)
        if resultados == None or resultados == () or len(resultados) == 0:
            #como no se ha encontrado info de STOCK...
            for fila in xrange(self.grid1.GetNumberRows()):
                if self.grid1.GetCellValue(fila,0) == "": continue
                sucursal = self.grid1.GetCellValue(fila,0)
                stock = self.grid1.GetCellValue(fila,1)
                r1 = "INSERT INTO stock(ptc,sucursal,stock) "
                r2 = "VALUES('"+ptc+"','"+sucursal+"','"+stock+"')"
                sql = r1+r2
                sql3.append(sql)

        try:
            consultasBD.begin()
            if sql1 != "":consultasBD.executaSinCommit(None, sql1)
            if sql2 != "":consultasBD.executaSinCommit(None, sql2)
            if sql3 != []:
                for sql in sql3:
                    consultasBD.executaSinCommit(None, sql)
            consultasBD.commit()
            utiles.mensaje(None,"PTC normalizado.\nIntente recepcionar la Transferencia")
        except:
            consultasBD.rollback()
            utiles.mensaje(None,"Error: no pudo normalizarse el PTC "+ptc)

        self.OnLimpiar(None)
        